<template>
	<div class = "search">
		<input type="text" placeholder = "输入城市名或拼音" v-model = "keyword" @focus = "hasFocus" @blur = "hasFocus">
		<div class = "wrapper" ref="wrapper" v-show = "showCities">
			<ul>
				<li v-for = "item of list" :key = "item.id" class = "border-bottom" @click = "chooseCity(item.name)">{{item.name}}</li>
				<li class = "border-bottom" v-show = "hasNoData">未找到匹配城市</li>
			</ul>
		</div>
	</div>
</template>

<script>
	import BScroll from 'better-scroll'
	import { mapState,mapMutations } from 'vuex'
	export default {
		name : 'citySearch',
		props : ["cities"],
		data () {
			return {
				keyword : "",
				list : [],
				timer: null,
				hasNoData:false
			}
		},
		methods : {
			...mapMutations(['changeCity']),
			chooseCity (city) {
				this.changeCity(city);
				this.keyword = "";
				this.$router.push("/");
			},
			hasFocus () {
				this.$emit ('hideAlphabet');
			}
		},
		computed : {
			showCities () {
				return this.keyword;
			}
		},
		watch : {
			keyword () {
				if(this.timer){
					clearTimeout(this.timer);
				}
				if(!this.keyword){
					this.list = [];
					return;
				}
				this.timer = setTimeout(() => {
					const temp = []
					for(let i in this.cities){
						for(let k of this.cities[i]){
							if(k.spell.indexOf(this.keyword) > -1 || k.name.indexOf(this.keyword) > -1){
								temp.push(k);
							}
						}
					}
					if(temp.length){
						this.hasNoData = false;
					}else {
						this.hasNoData = true;
					}
					this.list = temp;
				},100)
			}
		},
		mounted () {
			this.scroll = new BScroll(this.$refs.wrapper,{
				click:true
			})
		}
	}
</script>

<style scoped lang = 'less'>
	@import '~css/variable.less';
	.search {
		height:.7rem;
		background: @bgColor;
		padding:0 .1rem .1rem;
		box-sizing: border-box;
		input {
			width: 100%;
			height:100%;
			padding:0 .1rem;
			border-radius: .06rem;
			text-align:center;
			box-sizing: border-box;
			color:#666;
			font-size: .24rem;
		}
		.wrapper {
			overflow: hidden;
			position: absolute;
			top:1.58rem;
			left:0;
			right:0;
			bottom:0;
			background: #eee;
			z-index:1;
			li {
				line-height:.62rem;
				color:#666;
				background: #fff;
				padding-left:.2rem;
			}
		}
	}
</style>